package com.googlecode.perfectable.persistable.serialization;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import com.googlecode.perfectable.persistable.storage.Materializer;
import com.googlecode.perfectable.persistable.storage.Persister;
import com.googlecode.perfectable.persistable.storage.Storage;

public class ObjectSerializer implements Serializer {
	private static final Separator DEFAULT_SEPARATOR = CustomClassSeparator.INSTANCE;
	private final Materializer materializer;
	private Persister persister;
	private final Separator separator;

	public ObjectSerializer(Storage storage) {
		this(storage, storage, DEFAULT_SEPARATOR);
	}

	public ObjectSerializer(Storage storage, Separator separator) {
		this(storage, storage, separator);
	}

	public ObjectSerializer(Materializer materializer, Persister persister,
			Separator separator) {
		this.materializer = materializer;
		this.persister = persister;
		this.separator = separator;
	}

	@Override
	public Object read(InputStream source) throws IOException, ClassNotFoundException {
		try(ObjectInputStream stream = new PersistanceInputStream(source, this.materializer)) {
			return stream.readObject();
		}
	}

	@Override
	public void write(OutputStream sink, Object obj) throws IOException {
		try(ObjectOutputStream stream = new PersistanceOutputStream(sink, this.persister, this.separator, obj)) {
			stream.writeObject(obj);
		}
	}

	public void setPersister(Persister persister) {
		this.persister = persister;
	}
}
